package com.wuwen.ai.extension;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.usages.UsageTarget;
import com.intellij.usages.impl.rules.JavaUsageTypeProvider;
import com.intellij.usages.impl.rules.UsageType;
import com.intellij.usages.impl.rules.UsageTypeProvider;
import com.intellij.usages.impl.rules.UsageTypeProviderEx;
import com.wuwen.ai.extension.neo4j.Neo4jService;


public class AnalysisMethod extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) {
            return;
        }
        Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
        CaretModel caretModel = editor.getCaretModel();
        PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
        PsiFile psiFile = psiDocumentManager.getPsiFile(editor.getDocument());
        if (psiFile == null) {
            return;
        }
        PsiElement elementAt = psiFile.findElementAt(caretModel.getOffset());
        if (elementAt == null) {
            return;
        }
        PsiElement parent = elementAt.getParent();
        // 查找PsiMethod
        PsiMethod psiMethod = null;
        while (parent != null) {
            if (parent instanceof PsiMethod method) {
                psiMethod = method;
                break;
            }
            // 逐级上查直到找到方法
            parent = parent.getParent();
        }
        if (psiMethod == null) {
//            Messages.showInfoMessage("Find failed!", "当前坐标所属方法");
            return;
        }
//        Messages.showInfoMessage(psiMethod.toString(), "当前坐标所属方法");
        Neo4jService instance = Neo4jService.INSTANCE();
        instance.addNeo4J();
        instance.queryNeo4JAll();
//        for(UsageTypeProvider provider: UsageTypeProvider.EP_NAME.getExtensionList()) {
//            UsageType usageType;
//            if (provider instanceof JavaUsageTypeProvider javaProvider) {
//                usageType = javaProvider.getUsageType(psiMethod, new UsageTarget[]{});
//            }
//            else {
//                usageType = provider.getUsageType(element);
//            }
//            if (usageType != null) {
//                return usageType;
//            }
//        }
    }
}
